import { OneModal } from '@/components/one-ui';
import { IOneModalRef } from '@/pages/type';
import { Ref, useContext, useEffect, useRef, useState } from 'react';
import { ContractManageAPI } from '../common/type';
import { UpdateTableCommon } from './UpdateTableCommon';
import { ConractControllerContext, IContractsActionEnum } from '../common';
import { updateProcureoeDataGrid } from '../services';
import { updateSourceColumns } from '../mconfig';
import { getColorTextLoadMap, getKeyRouter, onCloseModalCommon } from '@/utils';
import { message } from 'antd';
import moment from 'moment';

export const OpenProcureoModal: React.FC<ContractManageAPI.IOpenProcureoModal> = ({ onClose, contractFormName }) => {
  /**弹框的ref*/
  const updateModalRef: Ref<IOneModalRef> = useRef(null);

  /** 获取上下文 */
  const { curRes, styleFixCls, contractDispatch, contarctJsonList, contractDetailInfo } = useContext(ConractControllerContext);

  /** 保存选中数据 */
  const [selectProcureInfo, setSelectProcureInfo] = useState<Record<string, any>>({});

  /** 获取列表 */
  const { data, params, loading, pagination, searchList, getManageData } = updateProcureoeDataGrid(curRes);

  /** 搜索 */
  const onSearch = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 重置 */
  const onReset = (payload: Record<string, any>) => {
    getManageData({ ...payload });
  };

  /** 点击选中 */
  const onSelectTable = (selectInfo: any) => {
    setSelectProcureInfo(selectInfo);
  };

  /** 分页change 方法 */
  const onPageChange = (current: number, pageSize: number) => {
    getManageData({ ...params, current, pageSize });
  };

  /** 初始化 */
  useEffect(() => {
    if (data?.rows?.length > 0) {
      const sourceInfo: Record<string, any> = contractFormName?.getFieldsValue();
      const selectRows: Record<string, any> = data?.rows?.find((item: any) => item?.id == sourceInfo?.sourceID);
      setSelectProcureInfo(selectRows);
    }
  }, [data?.rows]);

  /** 处理渲染物料清单 */
  const handSaveDetailList = (infoList: Record<string, any>[]) => {
    let selectDetailList: Record<string, any>[] = [];

    infoList?.forEach((item: any) => {
      const obj: Record<string, any> = {
        modifyFlag: '0',
        key: `detail-${getKeyRouter()}`,
        // key: item?.materialID,
        materialName: item?.fullName ? item?.fullName : null,
        specInfo: item?.specInfo ? item?.specInfo : null,
        expectNum: item?.expectNum ? item?.expectNum : 0,
        unitBusiness: item?.unitBusiness ? item?.unitBusiness : null,
        unitBusinessName: item?.unitBusinessName ? getColorTextLoadMap(item?.unitBusinessName)?.colorText : null,
        taxRate: item?.taxRate ? item?.taxRate : contractFormName?.getFieldValue('taxRate'),
        priceInTax: item?.expectPrice ? item?.expectPrice : 0,
        sumInTax: item?.expectSum ? item?.expectSum : null,
        deliveryTime: item?.deliveryTime ? item?.deliveryTime : null,
        deliveryAddress: item?.deliveryAddress ? item?.deliveryAddress : null,
        deliveryStyle: item?.deliveryStyle ? item?.deliveryStyle : null,
        materialID: item?.materialID ? item?.materialID : null,
        materialNum: item?.materialNum ? item?.materialNum : null,
        supplyType: item?.supplyType ? item?.supplyType : null,
      };
      selectDetailList?.push(obj);

      let oldDetail = contractDetailInfo?.detailList;
      let needDel: any = [];
      if (oldDetail && oldDetail.length > 0) {
        oldDetail.map((item) => {
          needDel.push({
            ...item,
            modifyFlag: '2',
          });
        });
      }

      console.log('oldDetail', oldDetail);

      contractDispatch({
        type: IContractsActionEnum.CONTRACT_JSONLIST,
        payload: {
          ...contarctJsonList,
          detailList: [...needDel, ...selectDetailList],
        },
      });

      contractFormName?.setFieldsValue({
        detailList: selectDetailList,
      });
    });
  };

  /** 保存 */
  const onSave = () => {
    if (selectProcureInfo && JSON.stringify(selectProcureInfo) != '{}') {
      // const detailInfo: Record<string, any> = contractFormName?.getFieldsValue()
      const newSelectInfo: Record<string, any> = {
        // ...detailInfo,
        // ...selectProcureInfo,
        supplyTypeName: getColorTextLoadMap(selectProcureInfo?.supplyTypeName)?.colorText,
        supplyWay: selectProcureInfo?.supplyWay,
        bidTime: selectProcureInfo?.bidedTime ? moment(selectProcureInfo?.bidedTime) : null,
        procureRealName: getColorTextLoadMap(selectProcureInfo?.procureRealName)?.colorText,
        procureReal: selectProcureInfo?.procureReal,
        sourceID: selectProcureInfo?.id,
        applyName: selectProcureInfo?.applyName,
        // bidedTime: selectProcureInfo?.bidedTime,
        supplyType: selectProcureInfo?.supplyType,
        purchProjectName: selectProcureInfo?.purchProjectName,
        purchProjectCode: selectProcureInfo?.purchProjectCode,
        applyID: selectProcureInfo?.applyID,
        applyCode: selectProcureInfo?.applyCode,
        sourceCode: selectProcureInfo?.sourceCode,
        projectCode: selectProcureInfo?.projectCode,
        projectName: selectProcureInfo?.projectName,
        procureOrg: selectProcureInfo?.procureOrg,
        procureOrgName: selectProcureInfo?.procureOrgName,
        purchaseURL: `id=${selectProcureInfo?.id}&&noticeCode=${selectProcureInfo?.noticeCode}&&applyID=${selectProcureInfo?.applyID}`,
      };

      contractFormName?.setFieldsValue({
        // ...detailInfo,
        ...newSelectInfo,
        // contractURL: detailInfo?.contractURL
      });

      // 初始化渲染物料列表
      if (selectProcureInfo?.mpurchaseSourceMaterialList?.length > 0) {
        handSaveDetailList(selectProcureInfo?.mpurchaseSourceMaterialList);
      }
      onCloseModalCommon(updateModalRef);
    } else {
      message.warning('请选择采购申请！');
    }
  };

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={updateModalRef}
      title={'选择采购申请'}
      onCancel={onClose}
      width={document.body.clientWidth * 0.65}
      bodyStyle={{
        height: document.body.clientHeight * 0.55,
        padding: 0,
      }}
      onOk={onSave}
    >
      <UpdateTableCommon
        styleFixCls={styleFixCls}
        searchProps={{
          searchList,
          onReset,
          onSearch,
        }}
        selectTablePorps={{
          onSelectTable,
          selectRowObjList: [selectProcureInfo],
        }}
        tableProps={{
          columns: updateSourceColumns(),
          loading,
          dataSource: data?.rows,
          pagination,
          onPageChange,
        }}
      />
    </OneModal>
  );
};
